package com.htjx.mall.controllers;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.htjx.mall.commons.api.Result;
import com.htjx.mall.commons.models.Addressee;
import com.htjx.mall.commons.models.CommonBean;
import com.htjx.mall.commons.models.Order;
import com.htjx.mall.commons.models.OrderGroup;
import com.htjx.mall.commons.models.User;
import com.htjx.mall.commons.models.cart.CartItem;
import com.htjx.mall.commons.models.enums.OrderStatus;
import com.htjx.mall.commons.models.enums.TradeStatus;
import com.htjx.mall.commons.models.user.Account;
import com.htjx.mall.commons.utils.page.TinyPage;
import com.htjx.mall.controllers.commonapi.AuthorizeList;
import com.htjx.mall.controllers.commonapi.Cart;
import com.htjx.mall.controllers.commonapi.CommonCookie;
import com.htjx.mall.services.AddresseeService;
import com.htjx.mall.services.OrderService;
import com.htjx.mall.services.SequenceManager;
import com.htjx.mall.services.UserService;
import com.htjx.mall.services.wallet.AccountService;
import com.htjx.mall.services.wallet.TicketService;

@Controller
@RequestMapping("/order")
public class OrderController {

	@Autowired
	private OrderService orderService;
	@Autowired
	private UserService userService;
	@Autowired
	private AddresseeService addresseeService;
	@Autowired
	private AccountService accountService;
	@Autowired
	private TicketService ticketService;
	@Autowired
	private SequenceManager sequenceManager;
	
	@RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public Result list(@RequestParam("page_size") int pageSize, @RequestParam("page_no")int pageNo, HttpServletRequest request) {
		long userId = AuthorizeList.getCurrentAuthUser(request);
		User user = userService.findUniqueBy("id", String.valueOf(userId));
		if(user == null) {
			return new Result(9,"查询失败");
		}
		
		OrderStatus orderStatus = CommonCookie.getOrderStatus(request);
		TinyPage<Order> page = new TinyPage<Order>(pageSize, pageNo);
		page = orderService.page(user, orderStatus, page);
		
		CommonBean commonBean = new CommonBean();
		commonBean.setIndex(orderStatus.getIndex());
		commonBean.setName(orderStatus.name());
		commonBean.setDescription(orderStatus.getDescription());
		
		Map<String, Object> retBody = new HashMap<String, Object>();
		retBody.put("page", page);
		retBody.put("common_bean", commonBean);
		
		Result result = new Result(0, "查询成功");
		result.setBody(retBody);
		return result;
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public Result list(@RequestParam("order_status") OrderStatus orderStatus, HttpServletResponse response) {
		CommonCookie.setOrderStatus(orderStatus, response);
		Result result = new Result(0, "查询成功");
		return result;
	}
	
	@RequestMapping(value = "/select/cart", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public Result orderCart(HttpServletRequest request, HttpServletResponse response) {
		long userId = AuthorizeList.getCurrentAuthUser(request);
		User user = userService.findUniqueBy("id", String.valueOf(userId));
		if(user == null) {
			return new Result(9,"下单失败");
		}
		
		Addressee addressee = addresseeService.selectById(user.getAddressee_id());
		
		Cart cart = CommonCookie.getCartFromCookie(request);
		List<CartItem> cartList = cart.getCartList();
		List<Order> orderList = new ArrayList<Order>();
		
		for(int i = 0; i < cartList.size(); i++) {
			CartItem cartItem = cartList.get(i);
			Order order = new Order();
			order.setUser_id(user.getId());
			order.setOrder_status(OrderStatus.paying);
			order.setSpecification_id(cartItem.getSpecification_id());
			order.setQuantity(cartItem.getQuantity());
			if(addressee != null) {
				String address = addressee.getProvince()+" "+addressee.getCity() + " "+addressee.getArea()+" "+ addressee.getAddress();
				order.setRec_name(addressee.getRec_name());
				order.setAddress(address);
				order.setPhone(addressee.getPhone());
			}
			order.setCreate_time(new Date());
			orderList.add(order);
		}
		
		//Cookie 设定
		List<Long> orderIdList = orderService.insertOrder(orderList);
		cart.removeAll();
		CommonCookie.setOrderIds(orderIdList, response);
		CommonCookie.setCartToCookie(cart, response);
		
		Result result = new Result(0, "下单成功");
		return result;
	}
	
	/**
	 * 从产品选择页不经过购物车
	 * 直接下单，
	 * **/
	@RequestMapping(value = "/direct", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public Result orderDirect(@RequestParam("specification_id")long specificationId, @RequestParam("quantity") int quantity, HttpServletRequest request, HttpServletResponse response) {
		long userId = AuthorizeList.getCurrentAuthUser(request);
		User user = userService.findUniqueBy("id", String.valueOf(userId));
		if(user == null) {
			return new Result(9,"下单失败");
		}
		
		Addressee addressee = addresseeService.selectById(user.getAddressee_id());
		
		List<Order> orderList = new ArrayList<Order>();
		
		Order order = new Order();
		order.setUser_id(user.getId());
		order.setOrder_status(OrderStatus.paying);
		order.setSpecification_id(specificationId);
		order.setQuantity(quantity);
		if(addressee != null) {
			String address = addressee.getProvince()+" "+addressee.getCity() + " "+addressee.getArea()+" "+ addressee.getAddress();
			order.setRec_name(addressee.getRec_name());
			order.setAddress(address);
			order.setPhone(addressee.getPhone());
		}
		order.setCreate_time(new Date());
		orderList.add(order);
		
		List<Long> orderIdList = orderService.insertOrder(orderList);
		CommonCookie.setOrderIds(orderIdList, response);
		
		Result result = new Result(0, "下单成功");
		return result;
	}
	
	@RequestMapping(value = "/confirm", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public Result orderConfirm(@RequestParam(required=false, value="use_gold_coin") boolean useGoldCoin, @RequestParam(required=false, value="use_cash") boolean useCash, HttpServletRequest request, HttpServletResponse response) {
		long userId = AuthorizeList.getCurrentAuthUser(request);
		User user = userService.findUniqueBy("id", String.valueOf(userId));
		if(user == null) {
			return new Result(9,"订单确认有误");
		}
		
		Addressee addressee = addresseeService.selectById(user.getAddressee_id());
		
		List<Long> orderIds = CommonCookie.getOrderIds(request);
		List<Order> orderList = orderService.selectOrder(orderIds);
		if(addressee != null) {
			String address = addressee.getProvince()+" "+addressee.getCity() + " "+addressee.getArea()+" "+ addressee.getAddress();
			for (Order order : orderList) {
				order.setRec_name(addressee.getRec_name());
				order.setAddress(address);
				order.setPhone(addressee.getPhone());
			}
			orderService.updateOrder(orderList);
		}
		
		// 查询账户中的可用现金余额
		Account account = accountService.selectOne(userId);

		OrderGroup orderGroup = new OrderGroup();
		orderGroup.setUser_id(userId);
		orderGroup.setOrderList(orderList);
		orderGroup.setAccount(account);
		
		orderGroup.setUse_gold_coin(useGoldCoin);
		orderGroup.setUse_cash(useCash);
		orderGroup.calc();
		
		CommonCookie.setOrderGroup(orderGroup, response);
		// 查询可用的抵用券
//		List<Ticket> ticketList = ticketService.selectTickets(user, new Date());
		Map<String, Object> retBody = new HashMap<String, Object>();
		retBody.put("addressee", addressee);
		retBody.put("orderList", orderList);
		retBody.put("orderGroup", orderGroup);
		retBody.put("account", account);
		retBody.put("leftGoldCoin", account.getGold_coin()-orderGroup.getGold_coin_used());
		retBody.put("leftCash", account.getCash().add(orderGroup.getCash_used().negate()));
//		retBody.put("ticketList", ticketList);
		
		Result result = new Result(0, "查询成功");
		result.setBody(retBody);
		return result;
	}
	
	@RequestMapping(value = "/detail", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public Result getOrderById(@RequestParam("id")long id) {
		
		Order order = orderService.selectOne(id);
		if(order == null) {
			return new Result(9, "查询订单失败");
		}
		
		Result result = new Result(0, "查询成功");
		result.setBody(order);
		return result;
	}
	
	@RequestMapping(value = "/update", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public Result update(@RequestParam("id")long id, @RequestParam("quantity") int quantity) {
		Order order = orderService.selectOne(id);
		if(order == null) {
			return new Result(9, "查询订单失败");
		}
		
		order.setQuantity(quantity);
		order.setUpdate_time(new Date());
		orderService.updateOne(order);
		Result result = new Result(0, "更新成功");
		return result;
	}
	
	@RequestMapping(value = "/cancel", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public Result delete(@RequestParam("id")long id) {
		orderService.deleteOne(id);
		Result result = new Result(0, "删除成功");
		return result;
	}
	
	/**
	 * 当用户在用户中心浏览订单，并选择支付一个订单时使用
	 * **/
	@RequestMapping(value = "/select", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public Result selectOrder(@RequestParam("id")long id , HttpServletRequest request, HttpServletResponse response) {
		long userId = AuthorizeList.getCurrentAuthUser(request);
		User user = userService.findUniqueBy("id", String.valueOf(userId));
		if(user == null) {
			return new Result(9,"下单失败");
		}
		
		List<Long> orderIdList = new ArrayList<Long>();
		orderIdList.add(id);
		CommonCookie.setOrderIds(orderIdList, response);
		
		Result result = new Result(0, "支付成功");
		return result;
	}
	/**
	 * 用户确认订单完成
	 * @throws Exception 
	 * **/
	@RequestMapping(value = "/confirm", method = RequestMethod.POST, produces = "application/json")
	@ResponseBody
	public Result orderConfirm(HttpServletRequest request, HttpServletResponse response) {
		long userId = AuthorizeList.getCurrentAuthUser(request);
		User user = userService.findUniqueBy("id", String.valueOf(userId));
		if(user == null) {
			return new Result(9,"支付失败");
		}
		
		OrderGroup orderGroup = CommonCookie.getOrderGroup(request);
		List<Order> orderList = orderGroup.getOrderList();
		
		if(orderList.size() < 1) {
			return new Result(9,"订单为空");
		}
		
		if(StringUtils.isBlank(orderList.get(0).getRec_name())) {
			return new Result(9,"收件人不能为空");
		}
		
		if(StringUtils.isBlank(orderList.get(0).getPhone())) {
			return new Result(9,"收件人手机不能为空");
		}
		
		if(StringUtils.isBlank(orderList.get(0).getAddress())) {
			return new Result(9,"收件人地址不能为空");
		}
		
		// order_group 
		orderGroup.setCreate_time(new Date());
		orderGroup.setTrade_status(TradeStatus.wait_paying);
		CommonCookie.setOrderGroup(null, response);
		// 新增order Group
		long orderGroupId = orderService.insertOrderGroup(user, orderGroup);
		Result result = new Result(0, "确认");
		result.setBody(orderGroupId);
		return result;
	}
}
